package com.meida.module.virbox.provider;

import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.JsonUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.virbox.provider.entity.AuthToken;
import com.meida.module.virbox.provider.licenseProvider.License;
import com.meida.module.virbox.provider.tokenProvider.jwt.H265JwtUtils;
import com.meida.module.virbox.provider.virboxProvider.service.LicenseProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * <b>功能名：AuthProvider</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-02-14 jiabing
 */
@Service
@Slf4j
public class AuthTokenProvider {

    public static String tokenCodeRedisKey = "AUTHTOKEN_KEY_TOKENCODE";

    public static String licenseRedisKey = "AUTHTOKEN_KEY_LICENSE";

    @Autowired
    private RedisUtils redisUtils;


    public static String licenseName = "license.lic";

    @Autowired
    private LicenseProvider licenseProvider;

    public AuthToken getLicense(){
        AuthToken token = null;
        Object obj = redisUtils.get(licenseRedisKey);
        if (FlymeUtils.isNotEmpty(obj)) {
            token = JsonUtils.jsonToBean(obj.toString(),AuthToken.class);
            if(FlymeUtils.isNotEmpty(token)){
                return token;
            }
        }
        //优先通过加密狗进行授权
        token = licenseProvider.getAuthToken();
        if(FlymeUtils.isEmpty(token)){
            try{
                String filePath  = System.getProperty("user.dir");
                token = License.loadLicense(new File(filePath+File.separator+licenseName));
            }catch (Exception e){
                log.error("获取license异常",e);
                return null;
            }
        }
        if(FlymeUtils.isNotEmpty(token)){
            redisUtils.set(licenseRedisKey,JsonUtils.beanToJson(token),60*60*3L);
        }
        return token;
    }

    public AuthToken readTokenFromTokenFile(File licenseFile){
        AuthToken token = License.loadLicense(licenseFile);
        return token;
    }

    public String getTokenCode(String deviceCode, String jwt, boolean cover) {
        String tokenCode = redisUtils.getString(tokenCodeRedisKey);
        if (FlymeUtils.isNotEmpty(tokenCode) && !cover) {
            return tokenCode;
        }
        try {
            tokenCode = H265JwtUtils.paseJWT(deviceCode, jwt);
            if (FlymeUtils.isNotEmpty(tokenCode)) {
                redisUtils.set(tokenCodeRedisKey, tokenCode, 60 * 60 * 3L);
            }
            return tokenCode;
        } catch (Exception e) {
            log.error("jwt解析异常", e);
        }
        return null;
    }


}
